var backupTimer = 1 * 1000;
var saveUrl = 'http://meemi.com/api3/p/save/json';
var encoder = encodeURIComponent;
var sourceUrl;
var sourceTitle;
var selectedText = '';
var savedContent;
var selectedCode = false;
var edited = false;

if( localStorage.saveContent )
//	{
	savedContent = JSON.parse( localStorage.saveContent );
//	restoreContent();
//	edited = true; }
else
	savedContent = {};

var currentSection = 'text';

// Function to run at opening
document.addEventListener( 'DOMContentLoaded', function() {
	
	// *************************************** //
	// Creating the top bar with notifications //
	// *************************************** //
	// Find section on popup
	var selectorDiv = $( '#selector' );
	// Parsing data retrieved from site
	var notification = JSON.parse( localStorage.notificationCount );
	
	// Iterate every notification
	$.each( notification, function( elName, elValue ) {
	// Create container for each notification
		var elDiv = $( '<div />' );
		elDiv.attr({ 
			'class': 'notify', 
			'ID': elName });
		// Creating link
		var elLink = $( '<a />' );
		elLink.attr({ 
			'class': 'hide', 
			'ID': 'new-' + elName,
			'href': '#' });
		// Create the image badge
		var elBadge = $( '<div />' );
		elBadge.attr({ 
			'class': 'badge round' });
		elBadge.html( elValue.toString());
		elLink.append( elBadge );
		elDiv.append( elLink );
		// Creating icons
		var elIcon
		elIcon = $( '<img />' );
		elIcon.attr({
			'src': 'icons/new-' + elName + '-on.png' });
		elLink.append( elIcon );
		elIcon = $( '<img />' );
		elIcon.attr({ 
			'class': 'hide', 
			'ID': 'disabled', 
			'src': 'icons/new-' + elName + '-off.png' });
		elDiv.append( elIcon );

		// Checking what icons need to be shown
		if( elValue > 0 )
			elLink.removeClass( 'hide' );
		else
			elIcon.removeClass( 'hide' );
			
		selectorDiv.append( elDiv );

		// Adding listener for "click" action to avoid Chrome Javascript Security Policy
		elLink.click( function() {
			openPage( 'only_new_' + elName );
		});
	});
	
	// *********** //
	// Random Meme //
	// *********** //
	if( localStorage.showRandomMeme == 'hide' )
		$( '#random-meme' ).addClass( 'hide' );
	else {
		writeLog( 'Showing Random Meme', LOG_MOREINFO );
		chrome.extension.sendMessage(
			{ 'validation': 'random-meme' },
			function( response ) {
				var memeType = response.meme_type;
				// Validating response
				if( !response ) {
					writeLog( 'Background page does\'t provide any Random Meme. Skipping.', LOG_WARNING );
					$( '#random-meme-text' ).append( '<i>Impossibile visualizzare il meme.</i>' );
					return;	}
				var memeLink = $( '<a />' );
				memeLink.attr({
					'href': '#'	});
				memeLink.click(
					function() {
						chrome.tabs.create({
							'url': 'http://meemi.com/'+ response.screen_name+ '/'+ response.id }) 
					});
				memeLink.append( memeType );
				$( '#random-meme-type' ).append( memeLink );
				// If it is an image set it
				if( memeType == "image" ) {
					var memeImage = $( '<img />' );
					memeImage.attr({
						'src': response.images[0].image,
						'width': '100%' });
					$( '#random-meme-image' ).append( memeImage );
					$( '#random-meme-image' ).removeClass( 'hide' ); };
				$( '#random-meme-text' ).append( response.content );
				$( '#random-meme-author' ).append( response.screen_name );
			});
	}
		
	
	// ********************************* //
	// Creating event listener for items //
	// ********************************* //
	// Adding listener to Home Button
	$( '#home-link' ).click( function() { openPage() } );
	
	// For each item in menu
	$( '.menu li a' ).each( function() {
		$( this ).click( function() {
		 showSection( $( this ).attr( 'id' ));
		 smartCompiler(); });
	});
	
	// Other links
	$( '#twitter-btn' ).click( function() { addTwitter(); });
	$( '#draft-btn' ).click( function() { addDraft(); });
	$( '#options-btn' ).click( function() {
		if ( $( '#opt' ).css( 'display' ) == 'none' ) $( '#opt' ).slideDown();
		else $( '#opt' ).slideUp();
	});
	$( '#source-check' ).click( function() {
		if( $( this ).hasClass( 'active' )) {
			$( '#fonte' ).attr( 'value', '' );
			$( this ).removeClass( 'active' ); }
		else { 
			$( '#fonte' ).attr( 'value', 'via: '+ sourceUrl );
			$( this ).addClass( 'active' ); }
	});
	$( '#date-picker' ).datetimepicker({
		'defaultDate': +7,
		'dateFormat': 'dd/mm/yy',
		'hourGrid': 6,
		'minuteGrid': 10,
		'stepMinute': 5,
		'onSelect':
			function( dateText, element ) {
				var date = dateText.substr( 0,10 );
				var time = dateText.substr( 11 );
				// Compiling hidden input
				$( '#event-hour' ).val( time.substr( 0,2 ));
				$( '#event-minute' ).val( time.substr( 3 ));
				$( '#event-day' ).val( date.substr( 0,2 ));
				$( '#event-month' ).val( date.substr( 3,2 ));
				$( '#event-year' ).val( date.substr( 6 )); }
		});
	
	
	// Send button
	$( '#send-meme-button' ).click( function() { submitForm(); });
	// OnChange input field
	$( 'input:text, input:hidden, textarea' ).keyup( function() { saveContent( $(this) ); });
	
	// ******************** //
	// Listener for script //
	// ******************** //
	// Injecting Script on page to get infos
	chrome.tabs.executeScript( null, { 'file': 'page-script.js', 'allFrames': true, });
	chrome.extension.onMessage.addListener(
		function( message, sender, undefined ) {
			writeLog( 'Received message.', LOG_INFO );
			// If received message has images
			if( message.validation == 'page-script' && message.imagesArray ) {
				writeLog( 'Retrieved images from web page.', LOG_MOREINFO );
				var imagesList = $( '#images-list' );
				var imagesArray = message.imagesArray;
				var imageEl;
				var labelDiv;
				var imageContainer;
				var maxDimThumbnail = 100; // Maybe let user to choose this value
				// Sorting images from bigger to smaller
				imagesArray.sort( 
					function( elA, elB ) {
						/*
						Array elements are sorted based on the relationship between each pair of elements "a" and "b" and the function's return value:
						Less than 0: Sort "a" to be a lower index than "b"
						Zero: "a" and "b" should be considered equal, and no sorting performed.
						Greater than 0: Sort "b" to be a lower index than "a".
						*/
						return( (elB.width * elB.height) - (elA.width * elA.height) );
					});
				// Creating HTML for each image
				$.each( imagesArray, function( index, element ) {
					// Skipping very little images
					if( element.width * element.height < 3600 )
						return 'skip';
					imageEl = $( '<img />' );
					imageEl.attr({
						'src': element.src,
						'id': 'image' });
					imageContainer = $( '<div />' );
					imageContainer.attr({
						'id': 'img-container' });
					// Resizing image
					if( element.width > element.height ) {
						imageEl.attr({
							'width': maxDimThumbnail,
							'height': ( maxDimThumbnail / element.width ) * element.height }); }
					else {
						imageEl.attr({
							'width': ( maxDimThumbnail / element.height ) * element.width,
							'heigh': maxDimThumbnail });}
					
					labelDiv = $( '<div />' );
					labelDiv.attr({
						'id': 'image-label' });
					labelDiv.append( element.width+ ':'+ element.height );
					
					imageEl.click( function() {
						$( '#f-image .selected' ).removeClass( 'selected' );
						$( '#img_url' ).val( this.src );
						$( this ).parent().addClass( 'selected' );	});
					
					imageContainer.append( imageEl );
					imageContainer.append( labelDiv );
					imagesList.append( imageContainer );
				});
			}
			// If received message has selected text
			if( message.validation == 'page-script' && message.selectedText ) {
				selectedText = message.selectedText;
				if( /^</.test( selectedText ) ) {
					selectedCode = true;
					if( /^<object/.test( selectedText ) ||
						/^<embed/.test( selectedText) ||
						/^<blockquote/.test( selectedText) ) {
							$( '#video_content' ).val( selectedText );
							showSection( 'video' ); }; 
					}}
			smartCompiler();
		});
		
	// ***************************** //
	// Setting value taken from page //
	// ***************************** //
	
	// Getting the URL and title of the selected tab
	chrome.tabs.getSelected( null, function( tab ) {
		sourceUrl = tab.url;
		sourceTitle = tab.title;
		
		// Setting the link Field of Video Meme and select automaticly video Type.
		if( youtubeId = sourceUrl.match( YOUTUBE_REGEXP )) {
			$( '#video_content' ).val( 'http://www.youtube.com/watch?v=' + youtubeId[1]);
			showSection( 'video' ); }
		else if( vimeoId = sourceUrl.match( VIMEO_REGEXP )) {
			$( '#video_content' ).val( sourceUrl );
			showSection( 'video' ); }

		smartCompiler(); });
});

function smartCompiler() {

	// if( edited ) return;

	var textContent = $( '#text_content' );
	
	// Setting url field for link meme
	$( '#link_url' ).val( sourceUrl );
	
	if( currentSection == 'quote' ) {
		$( '#quote_author' ).val( sourceTitle );
		if( !selectedCode )
			textContent.val( selectedText );
		else
			textContent.val( '[code]'+ selectedText+ '[/code]' ); }
	else if( currentSection == 'link' )
		if( selectedText && !selectedCode )
			textContent.val( selectedText+ ' ['+ sourceTitle+ ']' );
		else
			textContent.val( sourceTitle );
	else if( currentSection == 'event' ) {
		$( '#event_title' ).val( sourceTitle );
		if( !selectedCode )
			textContent.val( selectedText ); }
	else if( currentSection == 'video' ) {
		if( selectedCode )
			textContent.val( '[b]'+ sourceTitle+ '[/b]' );
		else if( selectedText )
			textContent.val( '[b]'+ sourceTitle+ '[/b][quote]'+ selectedText+ '[/quote]' );
		else
			textContent.val( '[b]'+ sourceTitle+ '[/b]' ); }
	else {
		textContent.val( '[b]'+ sourceTitle+ '[/b]' );
		// Checking if there is a selected text
		if( selectedText )
			if( selectedCode )
				textContent.val( textContent.val() + '[code]'+ selectedText+ '[/code]' );
			else
				textContent.val( textContent.val() + '[quote]'+ selectedText+ '[/quote]' );
	};
}


// *********************************** //
// Action in case of click on selector //
// *********************************** //
function openPage( page ) {
	// Check for right value
	if( !page )
		page = '';
	if( page == 'only_new_new_followers' )
		page = 'only_new_followers';
	// Getting all Tab in selected Windows.
	chrome.tabs.getAllInWindow( undefined, function( tabs ) {
		for( var i = 0, tab; tab = tabs[i]; i++ ) {
			// For each tab checking if there is a Meemi url
			if ( tab.url && isMeemiUrl( tab.url, getMeemiUrl( page ))) {
				chrome.tabs.reload( tab.id );
				chrome.tabs.update( tab.id, { active: true });
				return; }
		}
		// Otherways create a new tab with the Url.
		chrome.tabs.create({ url: getMeemiUrl( page ) });
	});
}

// Get the Meemi timeline Url for the saved username.
function getMeemiUrl( addings ) {
	if( !addings )
		addings = '';
	// return getMeemiAPIURL(null,localStorage.username,"/wf/" + addings)
	// Doing correction on API incoerence.
	if( addings == 'only_new_new_followers' )
		addings = 'only_new_followers';
	if( addings == 'only_new_memes_priv' )
		addings = 'only_new_memes_private';
	if( addings == 'only_new_replies_priv' )
		addings = 'only_new_replies_private';
	return 'http://meemi.com/' + localStorage.username + '/wf/' + addings;
}

// Valuate if the given url can be a Meemi page.
function isMeemiUrl( urlFrom, urlTo ) {
	return urlFrom.indexOf( urlTo ) == 0;
}

// Show section in popup
function showSection( newSection ) {
	$( '.menu li a' ).removeClass( 'active' );
	$( '#'+ newSection ).addClass( 'active' );

	$( '#f-' + currentSection ).slideUp( 'fast', function() {
		$( '#f-' + newSection ).slideDown();
		$( '#meme_type' ).val( newSection );
	});
	currentSection = newSection;
}

// Add the Twitter tag to crosspost it to Twitter.
// Need activation in Meemi Settings
function addTwitter() {
	$( '#text_content' ).val( 
		function( index, text ) { 
			// Check if already set and delete it.
			if( text.substr( 0,4 ) == '@tw ' )
				return text.replace( '@tw ', '' );
			// If not add it
			else
				// Check if set ad Draft and remove it.
				if( text.substr( 0,6 ) == 'draft#' )
					text = text.replace( 'draft#', '' );
				return '@tw '+ text;
	});
}

// Set Meme as Draft
function addDraft() {
	$( '#text_content' ).val( 
		function( index, text ) { 
			// Check if already set and delete it.
			if( text.substr( 0,6 ) == 'draft#' )
				return text.replace( 'draft#', '' );
			// If not add it
			else
				// Check if set ad Draft and remove it.
				if( text.substr( 0,4 ) == '@tw ' )
					text = text.replace( '@tw ', '' );
				return 'draft#'+ text;
	});
}

// ************ //
// Sending meme //
// ************ //

function submitForm() {
	var requestTimeout = 1000 * 15;
	var parameters = {
	'meemi_id': localStorage.username,
	'pwd': localStorage.password,
	'app_key': applicationKey };
	
	// Getting input field
	var memeType = $( '#meme_type' );
	var sendButton = $( '#send-meme-button' );
	
	sendButton.attr( 'disabled', 'disabled' );
	sendButton.html( 'Sending...' );
	
	// Getting textareas contents
	$.each( $( 'input' ), function( index, element ) { 
		if( element.value != '' )
			parameters[element.name] = element.value; });
	$.each( $( 'textarea' ), function( index, element ) { 
		if( element.value != '' )
			parameters[element.name] = element.value; });
	
	// Send meme
	$.ajax({
		'url': saveUrl,
		'type': 'POST',
		'data': parameters,
		'timeout': requestTimeout,
		'dataType': 'json',
		'success': function( data ) {
			writeLog( 'Meme sent, ID: '+ data.message.id_meme, LOG_INFO );
			// Remove previous handler for click.
			sendButton.off( 'click' );
			sendButton.html( 'Go to Meme' );
			sendButton.click( function() {
				chrome.tabs.create({
					'url': 'http://meemi.com/'+ localStorage.username+ '/'+ data.message.id_meme });
				window.close(); });
			sendButton.removeAttr( 'disabled' ); },
		// In case of failed sent.
		'error': function( xhr, textStatus, thrownError ) {
			writeLog( 'Failed to send Meme: '+ textStatus, LOG_ERROR );
			writeLog( 'Respons from server: '+ xhr.responseText );
			sendButton.html( 'Retry' );
			sendButton.removeAttr( 'disabled' ); }
	});
}

// **************** //
// Saving on change //
// **************** //

function saveContent( element ) {
	
	if( element ) {
		writeLog( 'Saving: '+ element.attr( 'id' )+ ' -> '+ element.val(), LOG_MOREINFO );
		savedContent[element.attr( 'id' )] = element.val();
		localStorage.savedContent = JSON.stringify( savedContent );
		return; }
	
	// Scanning all textareas
	$.each( $( 'textarea' ), 
		function( index, element ) {
			if( element.val() != '' && element.attr( 'id' ) != 0 ) {
				writeLog( 'Saving: '+ element.attr( 'id' )+ ' -> '+ element.val(), LOG_MOREINFO );
				savedContent[element.attr( 'id' )] = element.val(); }
		});
	// Scanning all input fields
	$.each( $( 'input:text, input:hidden' ),
		function( index, element ) {
			if( element.val() != '' && element.attr( 'id' ) != 0 ) {
			writeLog( 'Saving: '+ element.attr( 'id' )+ ' -> '+ element.val(), LOG_MOREINFO );
				savedContent[element.attr( 'id' )] = element.val(); }
		});
	
	localStorage.savedContent = JSON.stringify( savedContent );
	// edited = true;
}

function restoreContent() {
	$.each( savedContent, function( key, value ) {
		$( '#'+ key ).val( value );
	});
}
